﻿#include "httpform.h"
#include "ui_httpform.h"

HttpForm::HttpForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HttpForm)
{
    ui->setupUi(this);

    ui->m_url->setText("http://localhost:8090/springboot/user/addUser.do");

    ui->m_key1->setText("username");
    ui->m_key2->setText("loginname");

    connect(ui->m_cmbMethod, SIGNAL(currentTextChanged(QString)), this, SLOT(on_currentTextChanged(QString)));
    connect(ui->m_btnSelect, SIGNAL(clicked()), this, SLOT(on_selectFile()));
    connect(ui->m_btnSend, SIGNAL(clicked()), this, SLOT(on_send()));

    m_pNetworkAccessManager = new QNetworkAccessManager(this);

    ui->m_downloadUrl->setText("http://localhost:8090/springboot/file/download.do");

    connect(ui->m_btnDowbload, SIGNAL(clicked()), this, SLOT(on_download()));

    m_pSelectPathAction = ui->m_downloadPath->addAction(QIcon(":/images/folder_add.png"), QLineEdit::TrailingPosition);
    connect(m_pSelectPathAction, &QAction::triggered, this, &HttpForm::on_selectPath);

    m_pDownloadNetworkAccessManager = new QNetworkAccessManager(this);
}

HttpForm::~HttpForm()
{
    delete ui;
}

void HttpForm::on_currentTextChanged(const QString &text)
{
    qDebug() << text;
    if(text == "GET")
    {
        ui->m_url->setText("http://localhost:8090/springboot/user/addUser.do");
        ui->m_key1->setText("username");
        ui->m_key2->setText("loginname");
    }
    else if(text == "POST")
    {
        ui->m_url->setText("http://localhost:8090/springboot/file/uploadFile.do");
        ui->m_key1->setText("name");
        ui->m_key2->setText("upload");
    }

    ui->m_value1->clear();
    ui->m_value2->clear();
}

void HttpForm::on_selectFile()
{
    QString fileName = QFileDialog::getOpenFileName(this, QString::fromLocal8Bit("文件对话框！"), "F:", QString::fromLocal8Bit("图片文件(*png *jpg);;本本文件(*txt)"));

    ui->m_value2->setText(fileName);
    qDebug() << fileName;

    emit statusBarShow(QString::fromLocal8Bit("Http选择文件"));
}

void HttpForm::on_send()
{
    QString method = ui->m_cmbMethod->currentText();
    if(method == "GET")
    {
       httpGet();
    }
    else if(method == "POST")
    {
       httpPost();
    }
}

void HttpForm::httpGet()
{
    QNetworkAccessManager *accessManager = new QNetworkAccessManager(this);
    connect(accessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(on_replyFinished(QNetworkReply*)));
    QUrl qUrl(ui->m_url->text());
    QUrlQuery query;
    query.addQueryItem(ui->m_key1->text(), ui->m_value1->text());
    query.addQueryItem(ui->m_key2->text(), ui->m_value2->text());
    qUrl.setQuery(query);
    QNetworkRequest requst;
    requst.setUrl(qUrl);
    accessManager->get(requst);
}

void HttpForm::on_replyFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray qba = reply->readAll();
        ui->m_reply->appendPlainText(QString(qba));

        emit statusBarShow(QString::fromLocal8Bit("Http get请求成功"));
    }
}

void HttpForm::httpPost()
{
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    QHttpPart textPart;
    textPart.setHeader(QNetworkRequest::ContentDispositionHeader,
                       QVariant("form-data; name=\"" + ui->m_key1->text() + "\""));
    textPart.setBody(ui->m_value1->text().toUtf8());



    QFileInfo fileInfo(ui->m_value2->text());
    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader,
                        QVariant("image/jpeg"));
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader,
                        QVariant("form-data; name=\"" + ui->m_key2->text() + "\"; filename=\""+fileInfo.fileName()+"\""));

    QFile *file = new QFile(ui->m_value2->text());
    file->open(QIODevice::ReadOnly);
    imagePart.setBodyDevice(file);
    file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart

    multiPart->append(textPart);
    multiPart->append(imagePart);

    QUrl url(ui->m_url->text());
    QNetworkRequest request(url);

    QNetworkReply *m_pNetworkReply = m_pNetworkAccessManager->post(request, multiPart);

    QEventLoop eventLoop;
    connect(m_pNetworkAccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    eventLoop.exec();//block until finish


    if(m_pNetworkReply->error() == QNetworkReply::NoError)
    {
        QByteArray qba = m_pNetworkReply->readAll();
        ui->m_reply->appendPlainText(QString(qba));

        m_pNetworkReply->deleteLater();
        file->flush();
        file->close();

        emit statusBarShow(QString::fromLocal8Bit("Http post请求成功"));
    }
    else
    {
        m_pNetworkReply->deleteLater();
    }
}

void HttpForm::on_download()
{
    QEventLoop eventLoop;
    QObject::connect(m_pDownloadNetworkAccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    QNetworkRequest request;
    request.setUrl(QUrl(ui->m_downloadUrl->text()));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded; charset=utf-8");
    QNetworkReply *reply = m_pDownloadNetworkAccessManager->get(request);
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);

    if (reply->error() == QNetworkReply::NoError) {
        QString filename = reply->rawHeader("Content-Disposition");
        if(filename != nullptr && filename != "")
        {
            int index = filename.indexOf("filename=");
            filename = filename.mid(index + 9);
        }
        QByteArray qba = reply->readAll();

        QFile file(ui->m_downloadPath->text() + filename);
        if (file.open(QIODevice::ReadWrite))
        {
            file.write(qba);
            file.flush();
            file.close();

            emit statusBarShow(QString::fromLocal8Bit("Http下载成功"));
        }
    } else {
        qDebug() << reply->errorString(); //错误信息
    }
    reply->deleteLater();
}

void HttpForm::on_selectPath()
{
    QString dir = QFileDialog::getExistingDirectory(this, QString::fromLocal8Bit("文件对话框！"),
                                                      "E:/",
                                                      QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    ui->m_downloadPath->setText(dir);
}
